from flask import Flask, request,jsonify
from flask_cors import CORS
from models import db, User, Friend

app = Flask(__name__)

#配置当前应用允许跨域访问
CORS(app)

#配置数据库 URI  chat.db数据库文件默认存储在  instance目录下
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'

db.init_app(app)

#创建数据库表
with app.app_context():
    db.create_all()


@app.route('/register', methods=['POST'])
def register():
    try:
        # 接收数据
        username = request.get_json(force=True).get('userName')
        password = request.get_json(force=True).get('password')

        # 2,判断账号是否重复 （查询）
        u = User.query.filter_by(username=username).first()

        if (u):
            return jsonify({'success': False, 'message': '账号已经存在'})

        # 3,注册操作 （添加）
        # 密码加密
        password_hash = User.set_password(password)
        user = User(username=username, password_hash=password_hash)

        # 执行添加的操作
        db.session.add(user)
        db.session.commit()
        return jsonify({'success': True, 'message': '注册成功'})
    except ImportError as e:
        return jsonify({'error': False,'message':'注册失败，出错了!'})

@app.route('/login', methods=['POST'])
def login():
    try:
        username = request.get_json().get('userName')
        password = request.get_json().get('password')
        u = User.query.filter_by(username=username).first()
        if (u and u.check_password(password)):
            return jsonify({'success': True, 'message': '登录成功','user':u.to_dict()})
        else:
            return jsonify({'success': False, 'message': '账号或者密码错误'})
    except ImportError as e:
        return jsonify({'error': False,'message':'登录失败，出错了!'})

#查询当前登录用户的好友列表
@app.route('/get_friends', methods=['GET'])
def get_friends():
    try:
        user_id = request.args.get('userId')
        friends_list = Friend.query.filter_by(user_id=user_id).all()
        return jsonify({'success': True, 'friends': [f.to_dict() for f in friends_list]})
    except Exception as e:
        print(f'{e}')
        return jsonify({'success': False,'message':'查询好友列表失败，出错了!'})


@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!'


if __name__ == '__main__':
    app.run()
